package pl.edu.pw.polygen.modeler.client.workspace.listener;

import org.vaadin.gwtgraphics.client.shape.Rectangle;

import pl.edu.pw.polygen.modeler.client.utils.Scale;
import pl.edu.pw.polygen.modeler.client.workspace.IWorkspace;

import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseWheelEvent;

public class SelectListener extends BaseWorkspaceListener{

	private IWorkspace workspace;
	private Scale scale;
	private Rectangle rectangle;
	
	public SelectListener(IWorkspace workspace) {
		this.workspace = workspace;
		this.scale = Scale.getInstance();
	}

	@Override
	public void onMouseDown(MouseDownEvent event) {
		if(workspace.isMouseDownCatch()){
			workspace.setMouseDownCatch(false);
			
		}else{
			if(event.getNativeButton() == NativeEvent.BUTTON_MIDDLE ){
				workspace.setHolded(true);
			}else{
				workspace.dropAll();
				workspace.unselectAll();
				workspace.setSelected(true);
				rectangle = new Rectangle(workspace.getMouseX(), workspace.getMouseY(), 0, 0);
				rectangle.setFillOpacity(0); // set Rectangle to be transparent
				rectangle.setStrokeOpacity(0.5);
				workspace.getCanvas().add(rectangle);
			}
		}
	}

	@Override
	public void onMouseMove(MouseMoveEvent event) {
		if(workspace.isHolded()){
			workspace.shiftTo(workspace.getMouseX(),workspace.getMouseY());
		}
		if(workspace.isSeleceted()){
			rectangle.setWidth(workspace.getMouseX() - rectangle.getX());
			rectangle.setHeight(workspace.getMouseY() - rectangle.getY());
		}
		
	}

	@Override
	public void onMouseUp(MouseUpEvent event) {
		if(event.getNativeButton() == NativeEvent.BUTTON_MIDDLE){
			workspace.setHolded(false);
		}else if(workspace.isSeleceted()){
				workspace.setSelected(false);
				workspace.getCanvas().remove(rectangle);
				int x1 = rectangle.getX();
				int y1 = rectangle.getY();
				int x2 = x1 + rectangle.getWidth();
				int y2 = y1 + rectangle.getHeight();
				workspace.selectObjects(x1, y1, x2, y2);
		}
	}

	@Override
	public void onMouseWheel(MouseWheelEvent event) {
		int delta = event.getDeltaY();
		workspace.zoom(delta);
	}

}
